package cn.jinjimi.app.main.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.annotation.ColorRes;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import cn.jinjimi.base.util.ToastUtils;
import cn.jinjimi.app.R;
import cn.jinjimi.app.controller.event.TagChangeEvent;
import cn.jinjimi.app.custom.entity.CustomTagData;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by NeXT on 15-7-29.
 */
public class TagView extends ViewGroup {

    private static final int TYPE_TEXT_NORMAL = 1;
    private List<CheckBox> tagChildViews = new ArrayList<>();
    private List<View> tagChildViews2 = new ArrayList<>();

    private LayoutInflater mInflater;
    private OnTagCheckListener onTagCheckListener;
    private onTagClickListener onTagClickListener;

    private int sizeWidth;
    private int sizeHeight;

    private float mTagSize;
    private int mTagColor;
    private int mTextColor1;
    private int mTextColor2;
    private int mBackground;

    private int mTagBorderHor;
    private int mTagBorderVer;

    private int paddingLeft;
    private int paddingRight;
    private int paddingTop;
    private int paddingBottom;

    private int mTagResId;
    private int mRightImageResId;
    private boolean mSingleLine;
    private boolean mShowRightImage;
    private boolean mShowEndText;
    private boolean mCanTagClick;
    private String endTextString;

    private int imageWidth;
    private int imageHeight;
    private ImageView imageView = null;

    private int endTextWidth = 0;
    private int endTextHeight = 0;
    private TextView endText = null;

    private static final int DEFAULT_VIEW_PADDING = 0;
    private static final int DEFAULT_TEXT_COLOR = Color.WHITE;
    private static final int DEFAULT_TEXT_SIZE = 14;
    private static final int DEFAULT_TEXT_BACKGROUND = R.drawable.tag_background;
    private static final int DEFAULT_TEXT_BORDER_HORIZONTAL = 8;
    private static final int DEFAULT_TEXT_BORDER_VERTICAL = 5;

    private static final int DEFAULT_TAG_RESID = R.layout.item_tag;
    private static final int DEFAULT_RIGHT_IMAGE = R.drawable.icon_right;
    private static final boolean DEFAULT_SINGLE_LINE = false;
    private static final boolean DEFAULT_SHOW_RIGHT_IMAGE = true;
    private static final boolean DEFAULT_SHOW_END_TEXT = true;
    private static final String DEFAULT_END_TEXT_STRING = " … ";
    private static final boolean DEFAULT_CAN_TAG_CLICK = true;
    PopupWindow mPopupWindow;

    public TagView(Context context) {
        this(context, null);
    }

    public TagView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TagView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        mInflater = LayoutInflater.from(context);

        TypedArray a = context.getTheme().obtainStyledAttributes(
                attrs,
                R.styleable.TagCloudView,
                defStyleAttr,
                defStyleAttr
        );

        mTagSize = a.getDimension(R.styleable.TagCloudView_tcvTextSize, DEFAULT_TEXT_SIZE);
        mTagColor = a.getColor(R.styleable.TagCloudView_tcvTextColor, DEFAULT_TEXT_COLOR);
        mTextColor1 = a.getColor(R.styleable.TagCloudView_tcvTextColor, ContextCompat.getColor(context, R.color.orange));
        mTextColor2 = a.getColor(R.styleable.TagCloudView_tcvTextColor, ContextCompat.getColor(context, R.color.color_selector_orange_white));
        mBackground = a.getResourceId(R.styleable.TagCloudView_tcvBackground, DEFAULT_TEXT_BACKGROUND);

        paddingTop = a.getDimensionPixelSize(R.styleable.TagCloudView_tcvPaddingTop, DEFAULT_VIEW_PADDING);
        paddingLeft = a.getDimensionPixelSize(R.styleable.TagCloudView_tcvPaddingLeft, DEFAULT_VIEW_PADDING);
        paddingRight = a.getDimensionPixelSize(R.styleable.TagCloudView_tcvPaddingRight, DEFAULT_VIEW_PADDING);
        paddingBottom = a.getDimensionPixelSize(R.styleable.TagCloudView_tcvPaddingBottom, DEFAULT_VIEW_PADDING);

        mTagBorderHor = a.getDimensionPixelSize(
                R.styleable.TagCloudView_tcvItemBorderHorizontal, DEFAULT_TEXT_BORDER_HORIZONTAL);
        mTagBorderVer = a.getDimensionPixelSize(
                R.styleable.TagCloudView_tcvItemBorderVertical, DEFAULT_TEXT_BORDER_VERTICAL);
        mCanTagClick = a.getBoolean(R.styleable.TagCloudView_tcvCanTagClick, DEFAULT_CAN_TAG_CLICK);

        mRightImageResId = a.getResourceId(R.styleable.TagCloudView_tcvRightResId, DEFAULT_RIGHT_IMAGE);
        mSingleLine = a.getBoolean(R.styleable.TagCloudView_tcvSingleLine, DEFAULT_SINGLE_LINE);
        mShowRightImage = a.getBoolean(R.styleable.TagCloudView_tcvShowRightImg, DEFAULT_SHOW_RIGHT_IMAGE);
        mShowEndText = a.getBoolean(R.styleable.TagCloudView_tcvShowEndText, DEFAULT_SHOW_END_TEXT);
        endTextString = a.getString(R.styleable.TagCloudView_tcvEndText);

        mTagResId = a.getResourceId(R.styleable.TagCloudView_tcvTagResId, DEFAULT_TAG_RESID);

        a.recycle();
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return (!mCanTagClick && mSingleLine) || super.onInterceptTouchEvent(ev);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
    }

    /**
     * 计算 ChildView 宽高
     *
     * @param widthMeasureSpec
     * @param heightMeasureSpec
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        /**
         * 计算 ViewGroup 上级容器为其推荐的宽高
         */
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
        sizeHeight = MeasureSpec.getSize(heightMeasureSpec);

        //计算 childView 宽高
        measureChildren(widthMeasureSpec, heightMeasureSpec);

        initSingleLineView(widthMeasureSpec, heightMeasureSpec);

        int totalWidth = 0;
        int totalHeight = 0;

        if (mSingleLine) {
            totalHeight = getSingleTotalHeight(totalWidth, totalHeight);
        } else {
            totalHeight = getMultiTotalHeight(totalWidth, totalHeight);
        }

        /**
         * 高度根据设置改变
         * 如果为 MATCH_PARENT 则充满父窗体，否则根据内容自定义高度
         */
        setMeasuredDimension(
                sizeWidth,
                (heightMode == MeasureSpec.EXACTLY ? sizeHeight : totalHeight));

    }

    /**
     * 初始化 singleLine 模式需要的视图
     *
     * @param widthMeasureSpec
     * @param heightMeasureSpec
     */
    private void initSingleLineView(int widthMeasureSpec, int heightMeasureSpec) {
        if (!mSingleLine) {
            return;
        }
        if (mShowRightImage) {
            imageView = new ImageView(getContext());
            imageView.setImageResource(mRightImageResId);
            imageView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
            measureChild(imageView, widthMeasureSpec, heightMeasureSpec);
            imageWidth = imageView.getMeasuredWidth();
            imageHeight = imageView.getMeasuredHeight();
            addView(imageView);
        }

        if (mShowEndText) {
            endText = (TextView) mInflater.inflate(mTagResId, null);
            if (mTagResId == DEFAULT_TAG_RESID) {
                endText.setBackgroundResource(mBackground);
                endText.setTextSize(TypedValue.COMPLEX_UNIT_SP, mTagSize);
                endText.setTextColor(mTagColor);
            }
            LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            endText.setLayoutParams(layoutParams);
            endText.setText(endTextString == null || endTextString.equals("") ? DEFAULT_END_TEXT_STRING : endTextString);
            measureChild(endText, widthMeasureSpec, heightMeasureSpec);
            endTextHeight = endText.getMeasuredHeight();
            endTextWidth = endText.getMeasuredWidth();
            addView(endText);
        }
    }

    /**
     * 为 singleLine 模式布局，并计算视图高度
     *
     * @param totalWidth
     * @param totalHeight
     * @return
     */
    private int getSingleTotalHeight(int totalWidth, int totalHeight) {
        int childWidth;
        int childHeight;

        totalWidth += paddingLeft;

        int textTotalWidth = getTextTotalWidth();
        if (textTotalWidth < sizeWidth - imageWidth) {
            endText = null;
            endTextWidth = 0;
        }

        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            childWidth = child.getMeasuredWidth();
            childHeight = child.getMeasuredHeight();


            if (i == 0) {
                totalWidth += childWidth;
                totalHeight = childHeight + paddingTop + paddingBottom;
            } else {
                totalWidth += childWidth + mTagBorderHor;
            }

            if (child.getTag() != null && (int) child.getTag() == TYPE_TEXT_NORMAL) {
                if (totalWidth + mTagBorderHor + paddingLeft + paddingRight + endTextWidth + imageWidth < sizeWidth) {
                    child.layout(
                            totalWidth - childWidth + mTagBorderVer,
                            totalHeight - childHeight,
                            totalWidth + mTagBorderVer,
                            totalHeight);
                } else {
                    totalWidth -= childWidth;
                    break;
                }
            }
        }

        if (endText != null) {
            endText.layout(
                    totalWidth + mTagBorderVer,
                    totalHeight - endTextHeight,
                    totalWidth + mTagBorderVer + endTextWidth,
                    totalHeight);
        }

        if (imageView != null) {
            imageView.layout(
                    sizeWidth - imageWidth,
                    (totalHeight - imageHeight) / 2,
                    sizeWidth,
                    (totalHeight - imageHeight) / 2 + imageHeight);
        }

        return totalHeight;
    }

    /**
     * 为 multiLine 模式布局，并计算视图高度
     *
     * @param totalWidth
     * @param totalHeight
     * @return
     */
    private int getMultiTotalHeight(int totalWidth, int totalHeight) {
        int childWidth;
        int childHeight;

        totalWidth += paddingLeft;
        totalHeight += paddingTop;

        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            childWidth = child.getMeasuredWidth();
            childHeight = child.getMeasuredHeight();

            totalWidth += childWidth;

            if (i == 0) {
                totalHeight += childHeight;
            } else {
                totalWidth += mTagBorderHor;
            }
            // + marginLeft 保证最右侧与 ViewGroup 右边距有边界
            if (totalWidth + paddingRight > sizeWidth) {
                totalWidth = paddingLeft;
                totalHeight += childHeight + mTagBorderVer;
                child.layout(
                        totalWidth,
                        totalHeight - childHeight,
                        totalWidth + childWidth,
                        totalHeight);
                totalWidth += childWidth;
            } else {
                child.layout(
                        totalWidth - childWidth,
                        totalHeight - childHeight,
                        totalWidth,
                        totalHeight);
            }
        }
        return totalHeight + paddingBottom;
    }

    private int getTextTotalWidth() {
        if (getChildCount() == 0) {
            return 0;
        }
        int totalChildWidth = 0;
        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            if (child.getTag() != null && (int) child.getTag() == TYPE_TEXT_NORMAL) {
                totalChildWidth += child.getMeasuredWidth() + mTagBorderHor;
            }

        }
        return totalChildWidth - mTagBorderHor + paddingLeft + paddingRight;
    }


    /***************************
     * 业务相关
     *****************************/
    /* 赚多保商品查询历史使用 */
    public void setStrTag(List<String> strings) {
        setStrTag(strings, null);
    }

    public void setStrTag(List<String> strings, List tagObjects) {
        if (strings != null && strings.size() > 0) {
            removeAllViews();
            tagChildViews2.clear();
            for (int i = strings.size() - 1; i > -1; i--) {
                final TextView checkView = (TextView) mInflater.inflate(R.layout.item_zdb_history_tag, null);

                checkView.setText(strings.get(i));
                LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                checkView.setLayoutParams(layoutParams);

                if (tagObjects != null && strings.size() == tagObjects.size()) {
                    checkView.setTag(tagObjects.get(i));
                } else {
                    checkView.setTag(strings.get(i));
                }

                checkView.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (onTagClickListener != null)
                            onTagClickListener.onTagClick(checkView.getTag());
                    }
                });
                checkView.setSingleLine();
                addView(checkView);
                tagChildViews2.add(checkView);
            }
        }
    }

    /**
     * 设置tag字体颜色
     * @param index
     * @param color
     */
    public void setStrTagTextColor(int index, @ColorRes int color) {
        int count = tagChildViews2.size();
        if (index < count) {
            View view = tagChildViews2.get(count - 1 - index);
            if (view instanceof TextView) {
                TextView tv = (TextView) view;
                tv.setTextColor(getResources().getColor(color));
            }
        }
    }

    public List<CheckBox> getTagChildView() {
        return tagChildViews;
    }

    public void setShowTag(List<CustomTagData> tagList) {
        if (tagList != null && tagList.size() > 0) {
            removeAllViews();
            tagChildViews.clear();

            for (CustomTagData data : tagList) {
                CheckBox checkView = (CheckBox) mInflater.inflate(R.layout.item_show_tag, null);
                checkView.setEnabled(false);

                setTagView(data, checkView);
            }
        }
        postInvalidate();
    }

    /* 设置标签页面上部内容 */
    public void setTagsInTopShow(List<CustomTagData> tagList) {
        if (tagList != null && tagList.size() > 0) {
            removeAllViews();
            tagChildViews.clear();

            for (CustomTagData data : tagList) {
                final CheckBox checkView;
                checkView = (CheckBox) mInflater.inflate(R.layout.item_tag, null);
                checkView.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        CustomTagData customTagData = (CustomTagData) v.getTag();
                        showPopupWindow(checkView, customTagData);
                    }
                });
                setTagView(data, checkView);
            }
        }
        postInvalidate();
    }

    /* 设置所有系统标签内容 */
    public void setTagsAll(List<CustomTagData> tagList) {
        if (tagList != null && tagList.size() > 0) {
            removeAllViews();
            tagChildViews.clear();

            for (CustomTagData data : tagList) {
                final CheckBox checkView = (CheckBox) mInflater.inflate(R.layout.item_select_tag, null);
                checkView.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        if (onTagCheckListener != null)
                            onTagCheckListener.onTagCheck(isChecked, (CustomTagData) checkView.getTag());
                    }
                });
                setTagView(data, checkView);
            }
        }

        postInvalidate();
    }

    /**
     * 为标签设置内容
     *
     * @param data
     * @param checkView
     */
    private void setTagView(CustomTagData data, CheckBox checkView) {
        checkView.setText(data.getName());
        LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        checkView.setLayoutParams(layoutParams);

        checkView.setTag(data);
        addView(checkView);
        tagChildViews.add(checkView);
    }

    /* 单个添加标签 */
    public boolean addTag(final CustomTagData data) {
        if (!data.getName().matches("^[\\u4E00-\\u9FA5A-Za-z0-9_-]+$")) {//只允许中文,英文,数字,- 和 _
            ToastUtils.toastMessage(getContext(), "请不要输入特殊字符");
            return false;
        }
        final CheckBox tagView = (CheckBox) mInflater.inflate(mTagResId, null);
        if (mTagResId == DEFAULT_TAG_RESID) {
            tagView.setBackgroundResource(mBackground);
        }
        LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        tagView.setLayoutParams(layoutParams);
        tagView.setText(data.getName());
        tagView.setTag(data);

        tagView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopupWindow(tagView, data);
            }
        });

        if (tagChildViews.size() == 0) {
            addView(tagView, 0);
        } else {
            addView(tagView, tagChildViews.size());
        }

        tagChildViews.add(tagView);

        return true;
    }

    /* 移除标签 */
    public void removeTag(CustomTagData data) {
        for (CheckBox checkBox : tagChildViews) {
            if (checkBox.getText().equals(data.getName())) {
                removeView(checkBox);
                tagChildViews.remove(checkBox);
                return;
            }
        }
    }

    /* 根据传进来的CustomTagData数组标记 */
    public void flagTag(boolean ifCheck, CustomTagData... customTagDatas) {
        for (CustomTagData data : customTagDatas) {
            for (CheckBox checkBox : tagChildViews) {
                if (checkBox.getText().equals(data.getName()))
                    checkBox.setChecked(ifCheck);
            }
        }
    }

    /**
     * 利用PopupWindow提示删除按钮,对标签进行移除.
     * 若移除的标签是从可选标签那里选择的,通知其进行UI更新
     *
     * @param tagView
     */
    private void showPopupWindow(final CheckBox tagView, final CustomTagData customTagData) {
        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(getContext()).inflate(
                R.layout.view_delete, null);
        mPopupWindow = new PopupWindow(contentView,
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true);
        // 设置按钮的点击事件
        TextView delete = (TextView) contentView.findViewById(R.id.txt_deleteTag);
        delete.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (customTagData.getId() == 0) {
                    removeTag(customTagData);//不用处理UI,下面的才要,这里没有ID.下面有
                } else {
                    EventBus.getDefault().post(new TagChangeEvent(customTagData));
                }
                mPopupWindow.dismiss();
            }
        });
        mPopupWindow.setTouchInterceptor(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                tagView.setChecked(false);
                return false;
            }
        });
        mPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        int[] location = new int[2];
        tagView.getLocationOnScreen(location);
        //让mPopupWindow展示于标签的上方
        mPopupWindow.showAtLocation(tagView, Gravity.NO_GRAVITY, location[0], location[1] - 11 / 6 * tagView.getHeight());
    }

    public void setOnTagCheckListener(OnTagCheckListener onTagCheckListener) {
        this.onTagCheckListener = onTagCheckListener;
    }

    public interface OnTagCheckListener {
        void onTagCheck(boolean isCheck, CustomTagData data);
    }

    public void setOnTagClickListener(onTagClickListener onTagClickListener) {
        this.onTagClickListener = onTagClickListener;
    }

    public interface onTagClickListener {
        void onTagClick(Object tag);
    }
}